package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.dto.UserDto;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;

    //验证码的短信
    @PostMapping("/sendMsg")
    public R<String> login(@RequestBody User user,HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        //判断手机号是不是为空

        if(!StringUtils.isEmpty(phone)){
            //随机生产4位验证码
            String s = ValidateCodeUtils.generateValidateCode(4).toString();

            //调用阿里云提供的api进行发送短信
            SMSUtils.sendMessage("瑞吉外卖","SMS_265590117",phone,s);

            //需要保存生成的验证码  保存到session里
            // session.setAttribute(phone,s);
            //TODO 需要把生成的验证码存储到redis里面
            //通过redis获取相应的操作对象  把code存储进redis里面  并且设置相应的有效时间
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(phone,s,5, TimeUnit.MINUTES);


            log.info(phone+"产生的验证码是："+s);
            return R.success("验证码发送成功！");
        }

        return R.error("手机号输入错误！");
    }

    //登录功能的实现  移动端用户登录
    @PostMapping("/login")
    public R<User> loginUser(@RequestBody UserDto userDto, HttpSession session){
        log.info("user登陆了："+userDto.toString());
        //获取手机号
        String phone = userDto.getPhone();

        //通过手机号查询session的验证码
//        String codeInSession = (String) session.getAttribute(phone);
        //TODO 修改部分
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        log.info("查询的code:"+codeInSession.toString());





        //比对两个验证码是否一致
        if (codeInSession!=null&&codeInSession.equals(userDto.getCode().toString())){

            //查询数据库  如果数据为空添加数据
            LambdaQueryWrapper<User> qw=new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User user = userService.getOne(qw);

            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //如果用户登录成功把redis里面的数据清除
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败，验证码错误！");
    }

    //退出方法
    @PostMapping("/loginout")
    public R<String> logOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功！");
    }
}
